"""
实验模板 API Schema
"""
from pydantic import BaseModel, Field, field_validator
from typing import Optional, List, Dict, Any
from datetime import datetime


class ExperimentTemplateCreate(BaseModel):
    """创建实验模板请求"""
    name: str = Field(..., description="模板名称", min_length=1, max_length=255)
    description: Optional[str] = Field(None, description="模板描述")
    yaml_content: str = Field(..., description="YAML 内容字符串", min_length=1)
    application_id: int = Field(..., description="所属应用ID")
    tags: Optional[List[str]] = Field(default=[], description="标签列表")
    created_by: Optional[str] = Field(None, description="创建人")

    @field_validator('name')
    @classmethod
    def name_must_not_be_empty(cls, v: str) -> str:
        if not v.strip():
            raise ValueError('模板名称不能为空')
        return v.strip()


class ExperimentTemplateUpdate(BaseModel):
    """更新实验模板请求"""
    name: Optional[str] = Field(None, description="新名称", min_length=1, max_length=255)
    description: Optional[str] = Field(None, description="新描述")
    yaml_content: Optional[str] = Field(None, description="新 YAML 内容", min_length=1)
    application_id: Optional[int] = Field(None, description="所属应用ID")
    change_log: Optional[str] = Field(None, description="修改说明")
    tags: Optional[List[str]] = Field(None, description="标签列表")


class ExperimentTemplateResponse(BaseModel):
    """实验模板响应(列表项)"""
    id: int
    name: str
    description: Optional[str] = None
    application_id: int
    tags: List[str] = []
    version: int
    created_at: datetime
    updated_at: datetime

    model_config = {"from_attributes": True}


class ExperimentTemplateListResponse(BaseModel):
    """实验模板列表响应"""
    total: int
    page: int
    page_size: int
    items: List[ExperimentTemplateResponse]


class VersionInfo(BaseModel):
    """版本信息"""
    version: int
    created_at: datetime
    change_log: Optional[str] = None


class ExperimentTemplateDetailResponse(BaseModel):
    """实验模板详情响应"""
    id: int
    name: str
    description: Optional[str] = None
    yaml_content: str
    json_config: Dict[str, Any]
    application_id: int
    tags: List[str] = []
    version: int
    version_history: List[VersionInfo] = []
    created_at: datetime
    updated_at: datetime
    created_by: Optional[str] = None

    model_config = {"from_attributes": True}


class VersionDiffResponse(BaseModel):
    """版本对比响应"""
    version1: Dict[str, Any]
    version2: Dict[str, Any]
    diff: str
